package goods

import (
	"fmt"
	"math"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

func GetNewProductRecommendation(id int64) []map[string]interface{} { // 获取新品推荐,根据创建的时间进行排序

	var NewProductRecommendationMap []map[string]interface{}
	ret := global.App.DB.Model(&model.GoodsSKU{}).Select("id", "name", "price", "image").
		Where("goods_type_id = ?", id).Order("created_at desc").
		Limit(2).Find(&NewProductRecommendationMap)
	if ret.RowsAffected == 0 {
		return nil
	}
	return NewProductRecommendationMap
}

func getNewGoodsList(pageSize, offset int, goodsType_id int64, sortType string) []map[string]interface{} { // 获取商品列表
	var NewGoodsListMap []map[string]interface{}
	switch sortType {
	case "default":
		sortType = "created_at"
	case "price":
		sortType = "price"
	case "sales":
		sortType = "sales"
	default:
		sortType = "created_at"
	}
	ret := global.App.DB.Model(&model.GoodsSKU{}).
		Select("id", "name", "price", "unite", "image").
		Where("goods_type_id = ?", goodsType_id).
		Order(sortType).
		Limit(pageSize).
		Offset(offset).
		Find(&NewGoodsListMap)
	if ret.RowsAffected == 0 {
		return nil
	}
	return NewGoodsListMap
}

func ToGoodsList(ctx *gin.Context) { // 显示商品分类列表页
	// 获取cookies信息
	var NewUser model.User
	cookies, _ := ctx.Cookie("username")
	if cookies == "" {
		NewUser.Name = ""
	}
	if ret := global.App.DB.Where("name = ?", cookies).Find(&NewUser); ret.RowsAffected == 0 {
		NewUser.Name = ""
	}
	if !NewUser.IsActive {
		NewUser.Name = ""
	}

	// 查询redis中的购物车数量
	cartKey := fmt.Sprintf("cartKey_%d", NewUser.ID)
	cartNum, _ := global.App.RDB.HLen(ctx, cartKey).Result()

	// 根据请求的URL获取类型ID、页码ID、排序方式
	pageIndex, _ := strconv.ParseInt(ctx.Param("page"), 10, 64)
	sortType := ctx.Query("sort")
	goodsType_Id, _ := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if goodsType_Id >= 7 || goodsType_Id <= 0 {
		ctx.Redirect(http.StatusFound, "/ttsx/index")
		return
	}

	// 商品分类
	var NewGoodsType_list []model.GoodsType
	global.App.DB.Find(&NewGoodsType_list)
	global.App.Log.Sugar().Infof("商品分类信息: %v", NewGoodsType_list)

	// 获取新品
	goodsTypeId, _ := strconv.ParseInt(ctx.Param("id"), 10, 64)
	NewProductRecommendationMap := GetNewProductRecommendation(goodsTypeId)
	global.App.Log.Sugar().Infof("新品信息: %v", NewProductRecommendationMap)

	// 获取商品分类名称
	var goodsTypeName string
	for _, v := range NewGoodsType_list {
		if v.ID == int(goodsTypeId) {
			goodsTypeName = v.Name
		}
	}

	/*  分页显示商品列表  */
	// 定义每一页显示的个数
	pageSize := 2

	// 根据类型ID获取该类型商品的全部数量
	var goodsTypeNum int64
	global.App.DB.Model(&model.GoodsSKU{}).Where("goods_type_id = ?", goodsTypeId).Count(&goodsTypeNum)
	global.App.Log.Sugar().Infof("Count: %d", goodsTypeNum)

	// 根据商品数量 和 每页显示的个数，计算需要的总页数
	pageCount := int64(math.Ceil(float64(goodsTypeNum) / float64(pageSize)))
	global.App.Log.Sugar().Infof("pageCount: %d", pageCount)

	// 根据 总页数 和 请求的页码 生成分页列表
	pages := utils.PageTool(int(pageCount), int(pageIndex))
	global.App.Log.Sugar().Infof("pages: %v", pages)

	// 获取上一页和下一页
	startPage := pageIndex - 1
	if startPage <= 1 {
		startPage = 1
	}

	nextPage := pageIndex + 1
	if nextPage > pageCount {
		nextPage = pageCount
	}

	// 获取商品列表
	offset := int((pageIndex - 1) * int64(pageSize))
	goodsList := getNewGoodsList(pageSize, offset, goodsTypeId, sortType)
	global.App.Log.Sugar().Infof("uid: %d, goodsList: %v", NewUser.ID, goodsList)

	ctx.HTML(http.StatusOK, "goods/list.html", map[string]interface{}{
		"Name":                     NewUser.Name,
		"IsActive":                 NewUser.IsActive,
		"GoodsTypeList":            NewGoodsType_list,
		"GoodsTypeId":              goodsTypeId,
		"PageIndex":                pageIndex,
		"SortType":                 sortType,
		"GoodsTypeName":            goodsTypeName,
		"ProductRecommendationMap": NewProductRecommendationMap,
		"Pages":                    pages,
		"StartPage":                startPage,
		"NextPage":                 nextPage,
		"GoodsList":                goodsList,
		"cartNum":                  cartNum,
	})
}

func ToGoodsDetail(ctx *gin.Context) { // 显示商品详情页
	// 获取cookies信息
	var NewUser model.User
	cookies, _ := ctx.Cookie("username")
	if cookies == "" {
		NewUser.Name = ""
	}
	if ret := global.App.DB.Where("name = ?", cookies).Find(&NewUser); ret.RowsAffected == 0 {
		NewUser.Name = ""
	}
	if !NewUser.IsActive {
		NewUser.Name = ""
	}

	// 查询redis中的购物车数量
	cartKey := fmt.Sprintf("cartKey_%d", NewUser.ID)
	cartNum, _ := global.App.RDB.HLen(ctx, cartKey).Result()

	// 商品分类
	var NewGoodsType_list []model.GoodsType
	global.App.DB.Find(&NewGoodsType_list)
	global.App.Log.Sugar().Infof("商品分类信息: %v", NewGoodsType_list)

	// 获取商品id
	goodsSKU_id := ctx.Query("id")

	// 浏览记录加入redis
	historyKey := fmt.Sprintf("browsingHistory_%d", NewUser.ID)
	global.App.RDB.LPush(ctx, historyKey, goodsSKU_id).Result()
	global.App.Log.Sugar().Infof("uid: %d 增加浏览记录成功", NewUser.ID)

	// 根据商品ID查询sku表（image、name、price、desc、unite、stock）
	// 关联类型表，获取商品类型名称
	// 关联spu表，获取商品介绍详情
	var NewGoodsDetailMap map[string]interface{}
	global.App.DB.Model(&model.GoodsSKU{}).
		Select("tb_goods_sku.id as sku_id",
			"tb_goods_sku.name as sku_name",
			"tb_goods_sku.image as sku_image",
			"price", "unite", "stock", "desc",
			"tb_goods_type.id as type_id",
			"tb_goods_type.name as type_name",
			"tb_goods_spu.detail as spu_detail").
		Joins("left join tb_goods_type on tb_goods_type.id=tb_goods_sku.goods_type_id").
		Joins("left join tb_goods_spu on tb_goods_spu.id=tb_goods_sku.goods_spu_id").
		Where("tb_goods_sku.id = ?", goodsSKU_id).
		Scan(&NewGoodsDetailMap)
	global.App.Log.Sugar().Infof("uid: %d, NewGoodsDetailMap: %v", NewUser.ID, NewGoodsDetailMap)

	// 根据类型ID查询sku表生成新品推荐
	goodsTypeId := NewGoodsDetailMap["type_id"].(int64)
	NewProductRecommendationMap := GetNewProductRecommendation(goodsTypeId)
	global.App.Log.Sugar().Infof("uid: %d, NewProductRecommendationMap: %v", NewUser.ID, NewProductRecommendationMap)

	ctx.HTML(http.StatusOK, "goods/detail.html", map[string]interface{}{
		"Name":                     NewUser.Name,
		"IsActive":                 NewUser.IsActive,
		"GoodsTypeList":            NewGoodsType_list,
		"GoodsDetail":              NewGoodsDetailMap,
		"ProductRecommendationMap": NewProductRecommendationMap,
		"cartNum":                  cartNum,
	})
}

func DoSearch(ctx *gin.Context) { // 搜索框
	// 获取cookies信息
	var NewUser model.User
	cookies, _ := ctx.Cookie("username")
	if cookies == "" {
		NewUser.Name = ""
	}
	if ret := global.App.DB.Where("name = ?", cookies).Find(&NewUser); ret.RowsAffected == 0 {
		NewUser.Name = ""
	}
	if !NewUser.IsActive {
		NewUser.Name = ""
	}

	// 商品分类
	var NewGoodsType_list []model.GoodsType
	global.App.DB.Find(&NewGoodsType_list)
	global.App.Log.Sugar().Infof("商品分类信息: %v", NewGoodsType_list)

	// 获取搜索的关键字
	goods_name := ctx.Query("goods_name")

	// 根据关键字模糊查询
	var NewSearchGoods []model.GoodsSKU
	global.App.DB.Where("`name` like ?", "%"+goods_name+"%").Or("`desc` like ?", "%"+goods_name+"%").Find(&NewSearchGoods)
	global.App.Log.Sugar().Infof("uid: %d, NewSearchGoods: %v", NewUser.ID, NewSearchGoods)

	ctx.HTML(http.StatusOK, "goods/search.html", map[string]interface{}{
		"Name":          NewUser.Name,
		"IsActive":      NewUser.IsActive,
		"GoodsTypeList": NewGoodsType_list,
		"GoodsList":     NewSearchGoods,
	})
}
